//
//  OALoginViewController.m
//  OASystem
//  
//  Created by zhoupengfei on 15/3/23.
//  Copyright (c) 2015年 zpf. All rights reserved.
//

#import "OALoginViewController.h"
#import "Toast+UIView.h"
#import "HttpTools.h"
#import "MBProgressHUD.h"
#import "XmlParseHelper.h"
#import "AnjiMainViewController_Second.h"
#import "AuthHelper.h"
@interface OALoginViewController ()<UITextFieldDelegate,SangforSDKDelegate>
@property (nonatomic, strong) AuthHelper *helper;
@end

@implementation OALoginViewController

NSString *vpnIp =    @"61.175.232.5";  //vpn设备IP地址
NSString *userName = @"app";             //用户名认证的用户名
NSString *password = @"appapp";                //用户名认证的密码

NSString *certName = @"";     //导入证书名字，如果服务端没有设置证书认证可以不设置
NSString *certPwd =  @"";          //证书密码，如果服务端没有设置证书
-(void)viewWillAppear:(BOOL)animated{
 _helper = [[AuthHelper alloc] initWithHostAndPort:vpnIp port:443 delegate:self];

    [self.helper setAuthParam:@AUTO_LOGIN_OFF_KEY param:@"true"];
}
- (void)viewDidLoad {
    [super viewDidLoad];

 


    if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"userId"] length] !=0) {
        self.accountTextField.text = [[NSUserDefaults standardUserDefaults] objectForKey:@"userId"];
    }
    
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"pwdId"] length] !=0) {
        self.passwordTextField.text = [[NSUserDefaults standardUserDefaults] objectForKey:@"pwdId"];
    }
    
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"autoLogin"] isEqualToString:@"Y"]) {
        self.autoLogin.selected = YES;
    }
    
}

#pragma Mark VPNDelegate
- (void) onCallBack:(const VPN_RESULT_NO)vpnErrno authType:(const int)authType
{
    switch (vpnErrno)
    {
        case RESULT_VPN_INIT_FAIL:
            NSLog(@"Vpn Init failed!");
            break;
            
        case RESULT_VPN_AUTH_FAIL:
            [self.helper clearAuthParam:@SET_RND_CODE_STR];
            NSLog(@"Vpn auth failed!");
            break;
            
        case RESULT_VPN_INIT_SUCCESS:
            NSLog(@"Vpn init success!");
            //设置认证参数 用户名和密码以数值map的形式传入
            [self.helper setAuthParam:@PORPERTY_NamePasswordAuth_NAME param:userName];
            [self.helper setAuthParam:@PORPERTY_NamePasswordAuth_PASSWORD param:password];
            //开始用户名密码认证
            [self.helper loginVpn:SSL_AUTH_TYPE_PASSWORD];
            break;
        case RESULT_VPN_AUTH_SUCCESS:
            [self startOtherAuth:authType];
            break;
        case RESULT_VPN_AUTH_LOGOUT:
            NSLog(@"Vpn logout success!");
            break;
        case RESULT_VPN_OTHER:
            if (VPN_OTHER_RELOGIN_FAIL == (VPN_RESULT_OTHER_NO)authType) {
                NSLog(@"Vpn relogin failed, maybe network error");
            }
            break;
            
        case RESULT_VPN_NONE:
            break;
            
        default:
            break;
    }
}

- (void) startOtherAuth:(const int)authType
{
    NSArray *paths = nil;
    switch (authType)
    {
//            证书认证
        case SSL_AUTH_TYPE_CERTIFICATE:
            paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                        NSUserDomainMask, YES);
            
            if (nil != paths && [paths count] > 0)
            {
                NSString *dirPaths = [paths objectAtIndex:0];
                NSString *authPaths = [dirPaths stringByAppendingPathComponent:certName];
                NSLog(@"PATH = %@",authPaths);
                //P12证书路径
                [self.helper setAuthParam:@CERT_P12_FILE_NAME param:authPaths];
                //证书的密码
                [self.helper setAuthParam:@CERT_PASSWORD param:certPwd];
            }
            NSLog(@"Start Cert Auth!!!");
            break;
            
/** 用户名密码认证 */
        case SSL_AUTH_TYPE_PASSWORD:
            NSLog(@"Start Password Name Auth!!!");
            [self.helper setAuthParam:@PORPERTY_NamePasswordAuth_NAME param:userName];
            [self.helper setAuthParam:@PORPERTY_NamePasswordAuth_PASSWORD param:password];
            
            break;
/** 无认证 */
        case SSL_AUTH_TYPE_NONE:
            NSLog(@"Auth success!!!");
//             [self setin];
            return;
        default:
            NSLog(@"Other failed!!!");
            return;
    }
    [self.helper loginVpn:authType];
}


- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{

    [self.accountTextField resignFirstResponder];
    [self.passwordTextField resignFirstResponder];
}

//记住账号
- (IBAction)recordAction:(id)sender {
    
    self.recordPassWord.selected = !self.recordPassWord.selected;
    if (!self.recordPassWord.selected) {
        self.autoLogin.selected = self.recordPassWord.selected;
    }
    
} 


//记住密码
- (IBAction)autoLogin:(id)sender {
    self.autoLogin.selected = !self.autoLogin.selected;
}
- (void)setin{
 [self.accountTextField resignFirstResponder];
    [self.passwordTextField resignFirstResponder];
    
    if (self.accountTextField.text.length == 0) {
        [self.view makeToast:@"请输入账号"];
        return;
    }
    if (self.passwordTextField.text.length == 0) {
        [self.view makeToast:@"请输入密码"];
        return;
    }
//    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        NSString *strUrl = [self.accountTextField.text stringByReplacingOccurrencesOfString:@" " withString:@""];

    NSMutableDictionary * params = [NSMutableDictionary dictionary];
    [params setObject:self.accountTextField.text forKey:@"userId"];
    [params setObject:self.passwordTextField.text forKey:@"pwdId"];

    
    [HttpTools postWithURL:KAnJiLoginURL arrays:@[@{@"userId":strUrl},@{@"pwdId":self.passwordTextField.text}] method:@"validationUser" success:^(id JSON) {
       [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        XmlParseHelper * parse = [[XmlParseHelper alloc]initWithData:JSON];
        NSArray * dataArray = [parse selectNodes:@"errmsg"];
        NSString * resultTag = nil;
        if (dataArray.count) {
            NSDictionary * dic  = [dataArray lastObject];
            resultTag = dic[@"text"];
        }
         AnjiMainViewController_Second * mainVC = [self.storyboard instantiateViewControllerWithIdentifier:@"AnjiMainVC"];
        UINavigationController * navVC = [[UINavigationController alloc]initWithRootViewController:mainVC];
        switch ([resultTag integerValue]) {
            case 1:
                 [self.view makeToast:@"您的用户名不存在，请确认后再输"];
                break;
                case 2:
                self.view.window.rootViewController = navVC;

                //记住账号的
//                if (self.recordPassWord.selected) {
//                    [[NSUserDefaults standardUserDefaults] setObject:strUrl forKey:@"userId"];
//                    [[NSUserDefaults standardUserDefaults] setObject:self.passwordTextField.text forKey:@"pwdId"];
//                 
//                }else{
//                    [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:@"userId"];
//                    [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:@"pwdId"];
//                }
                
                [[NSUserDefaults standardUserDefaults] setObject:strUrl forKey:@"userId"];
                [[NSUserDefaults standardUserDefaults] setObject:self.passwordTextField.text forKey:@"pwdId"];
                //自动登录的
                if (!self.autoLogin.selected) {
                    [[NSUserDefaults standardUserDefaults] setObject:@"N" forKey:@"autoLogin"];
                }else{
                    [[NSUserDefaults standardUserDefaults] setObject:@"Y" forKey:@"autoLogin"];
                }
             
                break;
                case 3:
                [self.view makeToast:@"您的密码错误，请确认后再输"];
                break;
                case -1099:
                [self.view makeToast:@"抱歉，服务器出错"];
                break;
            default:
                break;
        }
        
    } failure:^(NSError *error) {
         [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
    }];


}
- (IBAction)LoginAction:(UIButton *)sender {
  if (self.accountTextField.text.length == 0) {
        [self.view makeToast:@"请输入账号"];
        return;
    }
    if (self.passwordTextField.text.length == 0) {
        [self.view makeToast:@"请输入密码"];
        return;
    }else{


MBProgressHUD * hud =  [MBProgressHUD showHUDAddedTo:self.view animated:YES];
                hud.labelText = @"正在登录,请稍等";
[NSThread sleepForTimeInterval:1.0];

                 [self setin];

    }
    }
   
//}




@end
